# -*-coding:UTF-8 -*-
import os
import jaydebeapi
import pyhs2
from config import hive_url, hive_port

libs = []
path = 'D:/hive_lib/backup/'
for jar in os.listdir(path):
    libs.append(path + jar)


def get_data_by_table(tablename, *args):
    global libs
    conn = jaydebeapi.connect('org.apache.hive.jdbc.HiveDriver',
                              [hive_url, args[0], args[0]],
                              libs)
    curs = conn.cursor()
    sql = "select * from mdl.%s" % tablename
    if tablename == 'mobilephone_location':
        if args[1] == '' and args[2] == '':
            sql = ' '.join([sql, ' limit 100'])
        else:
            tmp1 = 'city_id=' + args[1] if args[1] != '' else ''
            tmp2 = 'pre7nums=' + args[2] if args[2] != '' else ''
            tmp = [tmp1, tmp2]
            if '' in tmp:
                tmp.remove('')
            tmp = ' and '.join(tmp)
            sql = ' '.join([sql, 'where ', tmp])
    curs.execute(sql)
    columns = [{'title': columnname[0][columnname[0].index('.') + 1:]} for columnname in curs.description]
    result = dict()
    result['columns'] = columns
    result['dataset'] = curs.fetchall()
    curs.close()
    conn.close()
    return result


#
#
class HiveClient:
    def __init__(self, db_host, user, password, database, port=10000, authMechanism="PLAIN"):
        """
        create connection to hive server2
        """
        self._user = user
        self.conn = pyhs2.connect(host=db_host,
                                  port=port,
                                  authMechanism=authMechanism,
                                  user=user,
                                  password=password,
                                  database=database,
                                  )

    def query(self, sql):
        """
        query
        """
        with self.conn.cursor() as cursor:
            try:
                cursor.execute(sql)
                result = dict()
                columns = [{'title': columnname['columnName'][columnname['columnName'].index('.') + 1:]} for columnname
                           in
                           cursor.getSchema()]
                result['columns'] = columns
                result['dataset'] = cursor.fetchall()
                return result
            except Exception, e:
                print "hive select error,wrong user:", self._user, 'sql:', sql

    def close(self):
        """
        close connection
        """
        self.conn.close()


def get_data_by_table1(tablename, *args):
    hive_client = HiveClient(db_host=hive_url, port=hive_port, user=args[0],
                             password=args[0], database='default', authMechanism='PLAIN')
    sql = "select * from mdl.%s" % tablename
    if tablename == 'mobilephone_location':
        if args[1] == '' and args[2] == '':
            sql = ' '.join([sql, ' limit 100'])
        else:
            tmp1 = 'city_id=' + args[1] if args[1] != '' else ''
            tmp2 = 'pre7nums=' + args[2] if args[2] != '' else ''
            tmp = [tmp1, tmp2]
            if '' in tmp:
                tmp.remove('')
            tmp = ' and '.join(tmp)
            sql = ' '.join([sql, 'where ', tmp])

    return hive_client.query(sql)

# print get_data_by_table('mobilephone_location', '', '14')
# print get_data_by_table('province','shenguocheng','shenguocheng')
